﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;
using Dapper.Contrib.Extensions;
using IN.DataBase;
using IN.Util;

namespace IN.Module
{
    /// <summary>
    /// Industry Software
    /// Copyright (c) 2020-2022
    /// 创建人：吴松
    /// 日 期：2020.07.01
    /// 描 述：菜单功能 BLL
    /// </summary>
    public class Sys_MenuBll : BaseBLL<SYS_MenuEntity>
    {
        private readonly TB_AuthorizeBll AuthorizeBll = new TB_AuthorizeBll();
        private readonly Sys_ButtonBll ButtonBll = new Sys_ButtonBll();
        #region 获取数据
        /// <summary>
        /// 获取所有菜单列表数据
        /// </summary>
        /// <returns></returns>
        public new List<SYS_MenuEntity> GetListAll()
        {
            List<SYS_MenuEntity> menuEntity = base.GetListAll().OrderBy(t => t.MenuOrder).ToList();
            return menuEntity;
        }

        /// <summary>
        /// 获取所有菜单列表数据
        /// </summary>
        /// <returns></returns>
        public List<SYS_MenuEntity> GetMenuTreeListAll(string menuid ="")
        {
            string sql = $@"select * from [dbo].[SYS_Menu] where [ParentMenuID]='{menuid}'";
            List<SYS_MenuEntity> menuEntitys = base.iBaseService.GetBySQL(sql).ToList();

            for (int i = 0; i < menuEntitys.Count; i++)
            {
                //sql = $@"select * from [dbo].[SYS_Menu] where [ParentMenuID]='{menuEntitys[i].MenuID}'";
                //menuEntitys[i].SYS_MenuEntities = GetMenuTreeListAll(menuEntitys[i].MenuID);
            }
            return menuEntitys;
        }

        /// <summary>
        ///  获取功能列表的树形数据(带勾选框)
        /// </summary>
        /// <returns></returns>
        public List<TreeModel> GetMenuCheckTree()
        {
            List<SYS_MenuEntity> menulist = GetListAll();
            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in menulist)
            {
                TreeModel node = new TreeModel();
                node.id = item.MenuID;
                node.formname = item.FormName;
                node.text = item.Caption;
                node.viewmodel = item.ViewModel;
                node.value = item.ViewName;
                node.wpforwinform = item.WpfOrWinForm;
                node.formssembly = item.FormAssembly;
                node.isvisible = item.IsVisible == 1;
                node.autoshow = item.AutoShow == 1;
                node.showcheck = item.AutoShow == 1;
                node.checkstate = false;
                node.isexpand = (item.IsVisible == 1);
                node.Imageicon = item.MenuLogo;
                node.parentId = item.ParentMenuID;
                treeList.Add(node);
            }
            return treeList.ToTree();
        }

        /// <summary>
        /// 根据角色id 获取树形数据
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public List<TreeModel> GetMenuTreeByRoleID(string roleid)
        {

            List<SYS_MenuEntity> menulist = GetListAll().FindAll(t=>t.IsVisible==1);
            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var item in menulist)
            {
                TreeModel node = new TreeModel();
                node.id = item.MenuID;
                node.formname = item.FormName;
                node.text = item.Caption;
                node.viewmodel = item.ViewModel;
                node.value = item.ViewName;
                node.wpforwinform = item.WpfOrWinForm;
                node.formssembly = item.FormAssembly;
                node.ShowStyle = item.ShowStyle == 1;
                node.isvisible = item.IsVisible == 1;
                node.autoshow = item.AutoShow == 1;
                node.showcheck = item.AutoShow == 1;
                node.checkstate = false;
                node.isexpand = (item.IsVisible == 1);
                node.isDesignForm = (item.IsDesignForm == 1);
                node.Imageicon = item.MenuLogo;
                node.parentId = item.ParentMenuID;
                treeList.Add(node);
            }
            List<TB_AuthorizeEntity> authList = AuthorizeBll.GetListAll().FindAll(t => t.ObjectId.Equals(roleid) && t.ItemType == 1 && t.ObjectType == 1);
            if (!roleid.Equals("17D9A99A-668A-4E80-8F3F-F13DAE916D7E"))
            {
                treeList = treeList.FindAll(t => authList.Select(s => s.ItemId).Contains(t.id));
            }
            return treeList.ToTree();
        }

        /// <summary>
        /// 获取按钮列表树形数据
        /// </summary>
        /// <returns></returns>
        public List<TreeModel> GetButtonCheckTree(ObservableCollection<TreeModel> MenuTreeList)
        {
            List<SYS_MenuEntity> modulelist = GetListAll();
            List<TreeModel> treeList = new List<TreeModel>();
            foreach (var menu in modulelist)
            {
                TreeModel TreeModel = TreeDataMake.FindNode(MenuTreeList, menu.MenuID);
                if (TreeModel !=null && TreeModel.checkstate !=false)
                {
                    TreeModel node = new TreeModel();
                    node.id = menu.MenuID;
                    node.formname = menu.FormName;
                    node.text = menu.Caption;
                    node.value = menu.MenuID;
                    node.ShowStyle = menu.ShowStyle == 1;
                    node.showcheck = true;
                    node.checkstate = false;
                    node.isexpand = true;
                    node.Imageicon = menu.MenuLogo;
                    node.parentId = menu.ParentMenuID;
                    if (menu.Target != 1)
                    {
                        List<Sys_ButtonEntity> buttonList = ButtonBll.GetListAll().FindAll(t => t.ButtonMenuID.Equals(menu.MenuID));
                        if (buttonList.Count > 0)
                        {
                            treeList.Add(node);
                        }
                        foreach (var button in buttonList)
                        {
                            TreeModel buttonNode = new TreeModel();
                            buttonNode.id = button.ButtonID;
                            buttonNode.text = button.ButtonName;
                            buttonNode.value = button.ButtonID;
                            buttonNode.showcheck = true;
                            buttonNode.checkstate = false;
                            buttonNode.isexpand = true;
                            buttonNode.icon = "";
                            buttonNode.parentId = (menu.MenuID);
                            treeList.Add(buttonNode);
                        };
                    }
                    else
                    {
                        treeList.Add(node);
                    }
                }
                
            }
            return treeList.ToTree();
        }
        public Object GetCheckTree()
        {
            var menuList = this.GetMenuCheckTree();
            //var buttonList = moduleIBLL.GetButtonCheckTree();
            //var columnList = moduleIBLL.GetColumnCheckTree();
            //var formList = moduleIBLL.GetFormCheckTree();
            var jsonData = new
            {
                menuList,
                //buttonList,
                //columnList,
                //formList
            };
            return jsonData;
        }
        #endregion


        #region 提交数据
        /// <summary>
        /// 删除数据  
        /// </summary>
        /// <param name="KeyValue"></param>
        /// <returns></returns>
        public bool Delete(string KeyValue)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="menuEntity"></param>
        /// <returns></returns>
        public new bool Insert(SYS_MenuEntity entity)
        {
            bool res = false;
            try
            {
                if (string.IsNullOrEmpty(entity.MenuID))
                {
                    entity.Create();
                    base.Insert(entity);
                    res = true;
                }
                else
                {
                    res = base.Update(entity);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return res;
        }


        public bool UpdateOrAdd(SYS_MenuEntity menuEntity, IEnumerable<Sys_ButtonEntity> buttonEntities)
        {
            bool res = false;
            using (IDbConnection dbConnection = DbConnection)
            {
                IDbTransaction transaction = dbConnection.BeginTransaction();
                try
                {
                    if (string.IsNullOrEmpty(menuEntity.MenuID))
                    {
                        menuEntity.Create();
                        dbConnection.Insert(menuEntity, transaction);
                        res = true;
                    }
                    else
                    {
                        res = dbConnection.Update(menuEntity, transaction);

                    }
                    if (!res)
                    {
                        transaction.Rollback();
                        return res;
                    }
                    var sql = $"delete from SYS_Button where BUTTONMENUID= '{menuEntity.MenuID}'";
                    IDbCommand dbCommand = dbConnection.CreateCommand();
                    dbCommand.Transaction = transaction;
                    dbCommand.CommandText= sql;
                    dbCommand.ExecuteNonQuery();

                    //var sql = $"DELETE FROM [dbo].[SYS_Button] where ButtonMenuID= '{menuEntity.MenuID}'";
                    //dbConnection.Execute(sql: sql, param: null, transaction: transaction);

                    foreach (var item in buttonEntities)
                    {
                        if (string.IsNullOrEmpty(item.ButtonID))
                        {
                            item.Create();
                            item.ButtonMenuID = menuEntity.MenuID;
                            dbConnection.Insert(item, transaction);
                            res = true;

                        }
                        else
                        {
                            //res = dbConnection.Update(item, transaction);
                            item.ButtonMenuID = menuEntity.MenuID;
                            dbConnection.Insert(item, transaction);
                            res = true;
                        }
                        if (!res)
                        {
                            transaction.Rollback();
                            return res;
                        }
                    }

                    transaction.Commit();

                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    MessageBox.Show(ex.Message);
                }
            }
            return res;
        }


        /// <summary>
        /// 删除数据 
        /// </summary>
        /// <param name="KeyValue"></param>
        /// <returns></returns>
        public bool Delete(SYS_MenuEntity menuEntity, IEnumerable<Sys_ButtonEntity> buttonEntities)
        {
            bool res = false;
            using (IDbConnection dbConnection = DbConnection)
            {
                IDbTransaction transaction = dbConnection.BeginTransaction();
                try
                {
                    res = dbConnection.Delete(menuEntity, transaction);
                    if (!res)
                    {
                        transaction.Rollback();
                        return res;
                    }
                    if (buttonEntities.Count() > 0)
                    {
                        res = dbConnection.Delete(buttonEntities, transaction);
                        if (!res)
                        {
                            transaction.Rollback();
                            return res;
                        }

                    }
                    transaction.Commit();

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    transaction.Rollback();
                }
            }
            return res;
        }
        #endregion
    }
}
